<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" width="720px">
		<el-form :model="formData" :rules="formRules" v-loading="loading" v-bind="formConfig" :validate-on-rule-change="false">
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="课题名称" prop="name">
						<el-select v-model="formData.name" filterable placeholder="请选择课题" :disabled="isManagerEdit">
							<el-option v-for="(item, index) in topicListData" :key="index" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="实验名称" prop="filed7">
						<el-autocomplete v-model="formData.filed7" v-bind="autocompleteConfig" @select="handleInputSelect" :disabled="isManagerEdit" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="开始时间" prop="startTime">
						<el-date-picker v-model="formData.startTime" type="date" value-format="yyyy-MM-dd" placeholder="实验开始时间"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="实验PI" prop="headName">
						<el-input v-model="formData.headName" placeholder="输入实验PI" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="测量技术" prop="expName">
						<el-select v-model="formData.expName" placeholder="选择测量技术" @change="handleStationChange">
							<el-option v-for="(item, index) in stationDatas" :key="index" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="房间" prop="room">
						<el-select v-model="formData.room" placeholder="选择房间">
							<el-option v-for="(item, index) in roomDatas" :key="index" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户" prop="userName">
						<el-input v-model="formData.userName" placeholder="请输入用户" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户单位" prop="source">
						<el-input v-model="formData.source" placeholder="请输入用户单位"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="预约机时" prop="filed3">
						<el-input-number v-model="formData.filed3" controls-position="right" placeholder="请输入预约机时"></el-input-number>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="液氦预约量" prop="filed1">
						<el-input-number v-model="formData.filed1" controls-position="right" :min="0" placeholder="请输入液氦预约量"></el-input-number>
						<span class="unit">升(L)</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="运维工程师" prop="filed8">
						<el-select v-model="formData.filed8" placeholder="请选择运维工程师">
							<el-option v-for="(item, index) in maintainUsers" :key="index" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="实验审核人" prop="auditId">
						<el-select v-model="formData.auditId" placeholder="请输入实验审核人">
							<el-option v-for="(item, index) in piUserData" :key="index" :label="item.userName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<template v-if="userRole !== 'manager'">
				<el-button size="medium" type="success" @click="handleSaveForm()" :loading="saveLoading">保存</el-button>
			</template>
			<el-button size="medium" type="warning" @click="handleSubmitForm()" :loading="submitLoading">确定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import moment from 'moment';
import { mapGetters } from 'vuex';
import { userDetail } from '@/api/system/tbSysUser';
import { queryUserRoleByType } from '@/api/system/tbSysUserRole';
import { queryAuditSelectList, queryPageList } from '@/api/business/tbTopic';
import { piStatDetail, addedPiStat, updatePiStat } from '@/api/business/tbPiStat';
import { queryAuditPageList, experimentDetail } from '@/api/business/tbExperiment';
export default {
	props: {
		value: { type: Boolean, default: false },
		dataId: { type: String, default: '' },
		userRole: { type: String, default: '' }
	},
	data() {
		return {
			visible: this.value,
			loading: false,
			formData: {},
			formRules: {
				name: { required: true, message: '请输入课题名称', trigger: 'change' },
				filed7: { required: true, message: '请输入实验名称', trigger: ['blur', 'change'] },
				startTime: { required: true, message: '请选择实验时间', trigger: 'change' },
				headName: { required: true, message: '请输入负责人', trigger: 'blur' },
				expName: { required: true, message: '请选择实验站', trigger: 'change' },
				room: { required: true, message: '请选择房间', trigger: 'change' },
				source: { required: true, message: '请输入用户单位', trigger: 'blur' },
				machineHour: { required: true, message: '请输入预约机时', trigger: 'blur' },
				filed1: { required: true, message: '请输入液氦预约量', trigger: ['blur', 'change'] },
				auditId: { required: true, message: '请选择实验审核人', trigger: 'change' },
				filed8: { required: true, message: '请选择运维工程师', trigger: 'change' }
			},
			formConfig: { ref: 'form', size: 'medium', labelWidth: '105px', class: 'principal_schedule_form' },
			piUserData: [],
			topicListData: [],
			saveLoading: false,
			submitLoading: false,
			autocompleteConfig: {
				triggerOnFocus: false,
				placeholder: '请输入实验名称',
				fetchSuggestions: this.handleFetchSuggestions
			}
		};
	},
	computed: {
		...mapGetters(['userInfo', 'siteConfig']),
		addOrEdit() {
			return !this.dataId;
		},
		dialogTitle() {
			return this.addOrEdit ? '添加实验安排' : '修改实验安排';
		},
		stationRooms() {
			return this.siteConfig.filter((n) => n.type === '6');
		},
		stationDatas() {
			return this.stationRooms.filter((n) => n.pid === '0');
		},
		roomDatas() {
			return this.stationRooms.filter((n) => n.pid === this.formData.expName);
		},
		maintainUsers() {
			return this.siteConfig.filter((n) => n.type === '7');
		},
		isManagerEdit() {
			return this.userRole === 'manager';
		},
		topicListFunction() {
			if (this.isManagerEdit) {
				return eval(queryPageList);
			} else {
				return eval(queryAuditSelectList);
			}
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible: {
			async handler(flag) {
				this.$emit('input', flag);
				if (!flag) return false;
				this.loading = true;
				await this.getPiUserData();
				await this.getTopicListData();
				if (this.addOrEdit) {
					this.formData = await this.initFormData();
					this.$refs['form'].resetFields();
				} else {
					this.formData = await this.getDataDetail();
					this.$set(
						this.formData,
						'expName',
						(() => {
							let station = this.stationDatas.find((n) => n.name === this.formData.expName);
							return station ? station.id : '';
						})()
					);
					this.$set(
						this.formData,
						'room',
						(() => {
							let room = this.roomDatas.find((n) => n.name === this.formData.room);
							return room ? room.id : '';
						})()
					);
				}
				this.loading = false;
			},
			immediate: true
		},
		'formData.name': {
			async handler(id) {
				if (!id) return false;
				let topicData = this.topicListData.find((n) => n.id === id);
				let userData = await this.getUserDetailData(topicData.createId);
				this.$set(this.formData, 'filed2', topicData.name);
				this.$set(this.formData, 'source', userData.filed2);
				this.$set(this.formData, 'userId', topicData.createId);
				this.$set(this.formData, 'userName', topicData.createName);
			}
		}
	},
	methods: {
		//初始化表单数据
		async initFormData() {
			let userInfo = this.userInfo;
			let formType = this.$route.query.type;
			let userData = await this.getUserDetailData(userInfo.id);
			let initData = { headId: userInfo.id, headName: userInfo.username };
			initData['auditId'] = userData.filed9;
			if (formType === '1') {
				initData['name'] = this.$route.query.id;
			} else if (formType === '2') {
				let expData = await this.getExperimentData();
				initData['filed7'] = expData.name;
				initData['name'] = expData.topicId;
				initData['filed3'] = this.getSurplusHours(expData);
			}
			return Promise.resolve(initData);
		},

		//获取课题数据
		async getTopicListData() {
			let audit = { audit: '1' };
			let query = { page: 1, limit: 9999999 };
			let params = this.isManagerEdit ? { ...query, ...audit } : audit;
			let result = await this.topicListFunction(params).then((res) => res.data);
			if (result.code === '0') {
				this.topicListData = result.data || [];
			}
		},

		//获取剩余时间
		getSurplusHours(data) {
			let userHours = Number(data.userHour || '0');
			let totalHours = Number(data.machineHour || '0');
			return totalHours - userHours;
		},

		//实验选择数据
		handleInputSelect(data) {
			this.$set(this.formData, 'filed3', this.getSurplusHours(data));
			this.$set(this.formData, 'filed10', data.id);
		},

		//获取实验详情
		async getExperimentData() {
			let id = this.$route.query.id;
			let result = await experimentDetail(id).then((res) => res.data);
			if (result.code === '0') {
				return Promise.resolve(this.$detailData(result.data));
			}
		},

		//获取PI数据
		async getPiUserData() {
			let params = { page: 1, limit: 99999, type: '3' };
			let result = await queryUserRoleByType(params).then((res) => res.data);
			if (result.code === '0') {
				this.piUserData = result.data || [];
			}
		},

		//获取用户详情
		async getUserDetailData(id) {
			let result = await userDetail(id).then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				return Promise.resolve(datas);
			}
		},

		//获取数据详情
		async getDataDetail() {
			let result = await piStatDetail(this.dataId).then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				return Promise.resolve(datas);
			}
		},

		//获取剩余时间
		getExcessTime(data) {
			return Number(data.machineHour) - Number(data.userHour);
		},

		handleStationChange() {
			this.$delete(this.formData, 'room');
			this.$nextTick(() => {
				this.$refs['form'].clearValidate('room');
			});
		},

		//保存
		handleSaveForm() {
			this.$refs['form'].validateField('name', (err) => {
				if (!!err) return false;
				this.saveLoading = true;
				this.submitFormRequest(2);
			});
		},

		//提交
		handleSubmitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				this.submitLoading = true;
				this.submitFormRequest(1);
			});
		},

		formatFormParams(isSave) {
			let roomId = this.formData.room;
			let expId = this.formData.expName;
			let maintainId = this.formData.filed8;
			let params = this.$deepClone(this.formData);
			let room = this.stationRooms.find((n) => n.id === roomId);
			let station = this.stationRooms.find((n) => n.id === expId);
			let maintain = this.maintainUsers.find((n) => n.id === maintainId);
			params['expName'] = !station ? '--' : station.name;
			params['room'] = !room ? '--' : room.name;
			params['filed9'] = maintain?.name;
			params['isSave'] = isSave;
			if (this.addOrEdit) {
				params['audit'] = '3';
				params['type'] = '1';
			}
			return params;
		},

		//提交表单请求
		async submitFormRequest(isSave) {
			let params = this.formatFormParams(isSave);
			let callFunction = eval(this.addOrEdit ? addedPiStat : updatePiStat);
			let result = await callFunction(params).then((res) => res.data);
			this.saveLoading = false;
			this.submitLoading = false;
			if (result.code === '0') {
				this.$showCustomMessage('success', `${this.addOrEdit ? '添加' : '修改'}数据成功`);
				this.visible = false;
				this.$emit('finish');
			}
		},

		//查询实验数据
		async handleFetchSuggestions(name, callback) {
			let params = { page: 1, limit: 99, topicId: this.formData.name, name };
			let result = await queryAuditPageList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				callback(datas.map((n) => ({ ...n, value: n.name })));
			} else {
				callback([]);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.principal_schedule_form::v-deep {
	width: 100%;
	overflow: hidden;
	padding: 10px 10px 0;
	.el-form-item__label {
		font-size: 16px;
	}
	.el-form-item__content {
		display: flex;
		align-items: center;
		.unit {
			flex-shrink: 0;
			margin-left: 10px;
		}
	}
	.el-input {
		font-size: 16px;
	}
	.el-select {
		width: 100%;
	}
	.is-controls-right {
		width: 100%;
	}
	.el-date-editor {
		width: 100%;
	}
	.el-autocomplete {
		width: 100%;
	}
}
</style>
